package com.aim.util;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: User
 * Date: 4/29/14
 * Time: 11:43 PM
 * To change this template use File | Settings | File Templates.
 */
public class Histogram {

    private double minValue;
    private double maxValue;
    private double interval;

    private double[] buckets;

    public Histogram(double minValue, double maxValue, int N) {
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.interval = (maxValue - minValue) / N;
        buckets = new double[N];
    }

    public void addValue(double value){
       addValue(value, 1);
    }

    public void addValue(double value, double amount){
        int index = (int)((value - minValue)/interval);
        if (index < 0){
            index = 0;
        } else if (index >= buckets.length){
            index = buckets.length - 1;
        }
        buckets[index] += amount;
    }

    public double[] getBuckets() {
        return buckets;
    }

    @Override
    public String toString() {
        return Arrays.toString(buckets);
    }

    public void smooth(int level) {
        double[] smoothed = new double [buckets.length];
        double sum = 0;
        for (int i = level/2; i < buckets.length - (level/2); i++) {
            for (int j = -level/2; j < level/2; j++) {
                sum += buckets[i+j];
            }
            smoothed[i] = sum/level;
        }
        buckets = smoothed;
    }

    public double[] getAccumulative(){
        double[] a = new double[buckets.length];

        a[0] = buckets[0];
        for (int i = 1; i < a.length; i++) {
            a[i] = a[i-1] + buckets[i];
        }
        return a;
    }

}
